package org.carpediem.conman.dao;

import org.carpediem.conman.entity.Firm;
import org.carpediem.schema.conman.BFirmInfo;
import org.carpediem.schema.conman.FirmInfo;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.sql.SQLException;
import java.util.List;

/**
 * @author Mark Petrovic
 */
public class FirmDaoImpl extends FirmDao {

    public Firm add(FirmInfo fInfo) {
        Firm firm = new Firm();
        BFirmInfo bInfo = fInfo.getFirm();
        firm.setUrl(bInfo.getUrl());
        firm.setCity(bInfo.getCity());
        firm.setKeywords(bInfo.getKeywords());
        firm.setNiche(bInfo.getNiche());
        firm.setName(bInfo.getName());
        hibernateTemplate.saveOrUpdate(firm);
        return firm;
    }

    public Firm getByUrl(String url) {
        return (Firm) hibernateTemplate.execute(new ByUrl(url));
    }

    public List<Firm> getAllFirms() {
        return hibernateTemplate.loadAll(Firm.class);
    }

    private class ByUrl implements HibernateCallback {
        private String url;

        public ByUrl(String url) {
            this.url = url.trim().toLowerCase();
        }

        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.createQuery("from Firm where url =:aUrl");
            query.setParameter("aUrl", url);
            return query.uniqueResult();
        }
    }
}
